import router from '../router'
import store from '../store'
import { Message } from 'element-ui'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'
import Cookies from 'js-cookie'
import { redirectToOA, getPageTitle } from '@/utils'

NProgress.configure({ showSpinner: false })

/**
 * 通过role判断是否与当前用户权限匹配
 * @param roles
 * @param routeRoles
 */
export function hasPermission(roles, routeRoles) {
  if (routeRoles.length > 0 && roles.length > 0) {
    return roles.some((role) => routeRoles.indexOf(role) >= 0)
  } else {
    return true
  }
}

router.beforeEach((to, from, next) => {
  NProgress.start()
  document.title = getPageTitle(to.meta.title)
  console.log('getToken()', getToken(), to)
  if (to.path === '/login') {
    next()
  } else {
    if (getToken()) {
      if (!store.getters.unid) {
        // 判断当前用户是否已拉取完user_info信息
        store
          .dispatch('GetInfo')
          .then((res) => {
            // 拉取user_info
            const roles = res.data.roles || []
            let toRoles = to.meta && to.meta.roles ? to.meta.roles : []
            console.log(res.data.roles)
            store.dispatch('GenerateRoutes', { roles }).then(() => {
              if (hasPermission(roles, toRoles)) {
                next()
              } else {
                Message.error('没权限！')
                next({ path: '/401' })
              }
            })
          })
          .catch((err) => {
            Message.error('请重新登录！')
            store.dispatch('FedLogOut').then(() => {
              Message.error(err)
              next({ path: '/' })
            })
          })
      } else {
        const roles = store.getters.roles || []
        console.log(store.getters)
        let toRoles = to.meta && to.meta.roles ? to.meta.roles : []

        if (hasPermission(roles, toRoles)) {
          next()
        } else {
          next({ path: '/401', replace: true, query: { noGoBack: true } })
        }
      }
      // NProgress.done()
      // next()
    } else {
      NProgress.done()
      next({ path: '/login' })
      // const _login = Cookies.get('token')
      // console.log('login', _login)
      // if (_login) {
      //   store
      //     .dispatch('Login', { _login })
      //     .then(() => {
      //       next(to)
      //     })
      //     .catch(() => {
      //       NProgress.done()
      //       console.log(1111111)
      //       // redirectToOA()
      //       next({ path: '/' })
      //     })
      // } else {
      //   NProgress.done()
      //   // redirectToOA()
      //   next({ path: '/login' })
      // }
    }
  }
})

router.afterEach(() => {
  NProgress.done() // 结束所有可能未结束的进度条
})
